package br.mikhas.util.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import br.mikhas.util.Assert;

/**
 * Extracts a single row from the {@link ResultSet}.
 * <p>
 * This implementation uses a {@link RowMapper} to map the result.
 * 
 * @author Mikhail Domanoski
 * 
 * @param <T>
 *            The type of object to be mapped
 */
class SingleRowResultSetExtractor<T> implements ResultSetExtrator<T> {

	private final RowMapper<T> rowMapper;

	/**
	 * Creates a new instance of {@link SingleRowResultSetExtractor} and defines
	 * the RowMapper to be used.
	 * 
	 * @param mapper
	 */
	SingleRowResultSetExtractor(RowMapper<T> mapper) {
		Assert.notNull(mapper);
		this.rowMapper = mapper;
	}

	/**
	 * Extracts a single row from the {@link ResultSet} using a
	 * {@link RowMapper}
	 */
	public T extractData(ResultSet rs) throws JdbcException {

		try {
			rs.next();
			return rowMapper.mapRow(0, rs);
		} catch (SQLException e) {
			throw new RowMappingException(
					"Error while mapping result set row #0", e);
		}
	}
}
